package com.my.micro.service.order.log;

import feign.Request;
import feign.slf4j.Slf4jLogger;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * curl log
 *
 * @author Zijian Liao
 * @since 1.0.0
 */
public class CurlLogger extends Slf4jLogger {

    private final Logger logger;

    public CurlLogger(Class<?> clazz) {
        super(clazz);
        this.logger = LoggerFactory.getLogger(clazz);
    }

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        if (logger.isDebugEnabled()) {
            logger.debug(toCurl(request.requestTemplate()));
        }
        super.logRequest(configKey, logLevel, request);
    }

    public String toCurl(feign.RequestTemplate template) {
        String headers = Arrays.stream(template.headers().entrySet().toArray())
                .map(header -> header.toString().replace('=', ':')
                        .replace('[', ' ')
                        .replace(']', ' '))
                .map(h -> String.format(" --header '%s' %n", h))
                .collect(Collectors.joining());
        String httpMethod = template.method().toUpperCase(Locale.ROOT);
        String url = template.url();
        if(template.body() != null){
            String body = new String(template.body(), StandardCharsets.UTF_8);
            return String.format("curl --location --request %s '%s' %n%s %n--data-raw '%s'", httpMethod, url, headers, body);
        }
        return String.format("curl --location --request %s '%s' %n%s", httpMethod, url, headers);
    }
}
